package com.enki.cigarettes.controller;

import com.enki.cigarettes.controller.vo.response.CouponResponseVo;
import com.enki.cigarettes.entity.CouponT;
import com.enki.cigarettes.entity.UserCouponT;
import com.enki.cigarettes.enums.CouponEnums;
import com.enki.cigarettes.handler.Response;
import com.enki.cigarettes.repository.CouponTRepository;
import com.enki.cigarettes.repository.UserCouponTRepository;
import com.enki.cigarettes.statics.StaticKeys;
import com.enki.cigarettes.utils.DateUtils;
import com.enki.cigarettes.utils.PrimaryKey;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.*;

/**
 * @author WCS.Wang
 * @version V1.0
 * @Package com.enki.cigarettes.controller
 * @Name e-cigarettes-shop-api-module
 * @Description: TODO 优惠券逻辑层
 * @date 2019-08-08
 */
@RestController
@RequestMapping("/api/coupons")
@Slf4j
public class CouponController {

    @Autowired
    UserCouponTRepository userCouponTRepository;
    @Autowired
    CouponTRepository couponTRepository;

    @ApiOperation(value = "获取可领优惠券")
    @GetMapping
    public Object findItems() {
        try {
            Sort sort = new Sort(Sort.Direction.DESC, StaticKeys.SORT_UPDATE_TIME);
            List<CouponT> beanItems = couponTRepository.findByStatusAndEffectiveEndTimeGreaterThan(true, new Date(), sort);
            List<CouponResponseVo> couponItems = new ArrayList<>();
            for (CouponT bean : beanItems) {
                CouponResponseVo couponItem = new CouponResponseVo();
                BeanUtils.copyProperties(bean, couponItem);
                couponItem.setTypeName(CouponEnums.CouponType.getName(bean.getType()));
                couponItem.setCouponScopeName(CouponEnums.CouponScope.getName(bean.getCouponScope()));
                Double percentage = (Double.valueOf(bean.getCouponAmount()) / Double.valueOf(bean.getCouponCount())) * 100;
                couponItem.setPercentage(percentage.intValue());
                couponItem.setId(bean.getId());
                couponItem.setUseTime(DateUtils.getDateYMD(bean.getEffectiveStartTime()) + " - " + DateUtils.getDateYMD(bean.getEffectiveEndTime()));
                couponItems.add(couponItem);
            }
            return Response.success(couponItems, StaticKeys.SUCCESS);
        } catch (Exception e) {
            log.error("获取可领取优惠券列表失败：" + e.getMessage());
            e.printStackTrace();
            return Response.serverError_500("获取可领取优惠券失败");
        }
    }

    @ApiOperation(value = "获取可领优惠券")
    @GetMapping(value = "/top2")
    public Object findItemsTop2() {
        try {
            Sort sort = new Sort(Sort.Direction.DESC, StaticKeys.SORT_UPDATE_TIME);
            List<CouponT> beanItems = couponTRepository.findTop2ByStatusAndEffectiveEndTimeGreaterThan(true, new Date(), sort);
            List<CouponResponseVo> couponItems = new ArrayList<>();
            for (CouponT bean : beanItems) {
                CouponResponseVo couponItem = new CouponResponseVo();
                BeanUtils.copyProperties(bean, couponItem);
                couponItem.setTypeName(CouponEnums.CouponType.getName(bean.getType()));
                couponItem.setCouponScopeName(CouponEnums.CouponScope.getName(bean.getCouponScope()));
                Double percentage = (Double.valueOf(bean.getCouponAmount()) / Double.valueOf(bean.getCouponCount())) * 100;
                couponItem.setPercentage(percentage.intValue());
                couponItem.setId(bean.getId());
                couponItem.setUseTime(DateUtils.getDateYMD(bean.getEffectiveStartTime()) + " - " + DateUtils.getDateYMD(bean.getEffectiveEndTime()));
                couponItems.add(couponItem);
            }
            return Response.success(couponItems, StaticKeys.SUCCESS);
        } catch (Exception e) {
            log.error("获取可领取优惠券列表失败：" + e.getMessage());
            e.printStackTrace();
            return Response.serverError_500("获取可领取优惠券失败");
        }
    }

    @ApiOperation(value = "领取优惠券")
    @GetMapping(value = "/receive/{id}")
    @Transactional
    public Object receiveCoupon(@PathVariable String id, HttpSession session) {
        try {
            Object sessionId = session.getAttribute(StaticKeys.USER_ID);
            if (sessionId == null) {
                return Response.unauthorized_401("登录身份失效，请重新登录");
            }
            CouponT bean = couponTRepository.findOneById(id);
            if (bean != null && bean.isStatus()) {
                if (bean.getCouponAmount() + 1 <= bean.getCouponCount()) {
                    if (bean.getCouponStint() != CouponEnums.CouponStint.INFINITE.getStint()) {
                        long couponCount = userCouponTRepository.countByUserIdAndCouponTId(sessionId.toString(), id);
                        if (couponCount >= bean.getCouponStint()) {
                            return Response.badRequest_400("此优惠券每人" + bean.getCouponScope() + "张");
                        }
                    }
                    UserCouponT userCoupon = new UserCouponT();
                    userCoupon.setId(PrimaryKey.get().toString());
                    userCoupon.setCouponTId(id);
                    userCoupon.setUserId(sessionId.toString());
                    userCoupon.setDataId(StaticKeys.NULL);
                    userCoupon.setStatus(false);
                    userCoupon.setCreateTime(new Date());
                    userCouponTRepository.save(userCoupon);
                    // 优惠券数量减一
                    bean.setCouponCount(bean.getCouponCount() - 1);
                    bean.setCouponAmount(bean.getCouponAmount() + 1);
                    bean.setUpdateTime(new Date());
                    couponTRepository.save(bean);
                }
            } else {
                return Response.notFound_404("此优惠券已领完");
            }
            return Response.success();
        } catch (Exception e) {
            log.error("领取优惠券失败：" + e.getMessage());
            e.printStackTrace();
            return Response.serverError_500("领取优惠券失败");
        }
    }

}
